﻿namespace BlogsAPI.Search
{
    using System.Text;
    using System.Text.RegularExpressions;
    using Abstract;
    using System.Web;
    using System.IO;
    using System.Net;
    using System.Diagnostics;
    using System;

    /// <summary>
    /// Класс для поиска в гугле 
    /// </summary>
    public class ImagesGoogle : BasicSearch
    {
        /// <summary>
        /// Конструктор
        /// </summary>
        public ImagesGoogle()
        {
        }

        /// <summary>
        /// ссылка для запросов. scoring=d - сортировка по дате
        /// </summary>
        protected virtual string SearchImageUrl
        {
            get
            {
                //return "http://www.google.ru/search?&q={0}&hl=ru&channel=suggest&biw=1920&bih=940&tbs=isz%3Am&tbm=isch&sa=1&btnG=%D0%9F%D0%BE%D0%B8%D1%81%D0%BA&aq=f&aqi=&aql=&gs_sm=s&gs_upl=27927l27927l1l28621l1l1l0l0l0l0l295l295l2-1l1l0";
                return "https://www.google.ru/search?q={0}&source=lnms&tbm=isch&channel=suggest";
            }
        }

        private static readonly Regex parser = new Regex(@"<img[^>]+src\W+([^""']+images[^""']+)[^>]*>", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);

        /// <summary>
        /// поиск в гугле-блогах
        /// </summary>
        /// <param name="text">текст для поиска</param>
        /// <param name="fromDate">дата начиная с которой искать объекты, может быть нулом, тогде по максимуму!</param>
        /// <returns>массив постов удовлетворяющих поиску</returns>
        public override BlogPost[] SearchFor(String text, DateTime? fromDate)
        {
            BlogPost[] oRes = new BlogPost[0];
            try
            {
                HttpWebRequest myHttpWebRequest = MakeRequest(String.Format(SearchImageUrl,HttpUtility.UrlEncode(text)));
                myHttpWebRequest.AllowAutoRedirect = false;
                myHttpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                myHttpWebRequest.Method = "GET";
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                string reply = (new StreamReader(myHttpWebResponse.GetResponseStream(), Encoding.UTF8)).ReadToEnd();
                myHttpWebResponse.Close();
                MatchCollection mc = parser.Matches(reply);
                if(mc.Count == 0)//redirect
                {
                    Regex rLink = new Regex(@"<a[^>]+href\W+(https[^>]+&sei=[^'""]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                    Match m = rLink.Match(reply);
                    if (m.Success)
                    {
                        myHttpWebRequest = MakeRequest(m.Groups[1].Value);
                        myHttpWebRequest.AllowAutoRedirect = false;
                        myHttpWebRequest.Method = "GET";
                        myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
                        reply = (new StreamReader(myHttpWebResponse.GetResponseStream(), Encoding.UTF8)).ReadToEnd();
                        myHttpWebResponse.Close();
                        mc = parser.Matches(reply);
                    }
                }
                if (mc.Count > 0)
                {
                    foreach (Match match in mc)
                    {
                        if(!match.Groups[1].Value.StartsWith("http")) continue;
                        BlogPost bp = BlogPost.SimpleLink(HttpUtility.UrlDecode(HttpUtility.UrlDecode(match.Groups[1].Value)));
                        if (bp != null)
                        {
                            Array.Resize(ref oRes, oRes.Length + 1);
                            oRes[oRes.Length - 1] = bp;
                        }
                        //пубем только 20 картинок возвращать!
                        if (oRes.Length == 20) break;
                    }
                }
            }
            catch (Exception e1)
            {
                Debug.WriteLine("SearchFor failed cause " + e1.Message);
            }
            return oRes;
        }
    }
}
